<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once 'dbconnect.php';
session_start();

$query = filter_input(INPUT_SERVER, 'QUERY_STRING');

//using jquery
if (isset($query)) {
    $query = str_replace("%3C", "<", $query);
    $query = str_replace("%3E", ">", $query);
    $array = explode("&", $query);
    if ($array[0] == "type=update") {
        update($array);
    } elseif ($array[0] == "type=delete") {
        delete($array);
    } else {
        echo $array[0];
    }
}

//using ajax
//get price of product by pid
if (isset($_POST['type'])) {
    if ($_POST['type'] == "getprice") {
        getPriceById($_POST['pid'], $_POST['quantity']);
    } else if ($_POST['type'] == "newImport") {
        insert();
    } else if ($_POST['type'] == "printImport") {
        printImportTable();
    }
}
// hiển thị modal khi click nút chi tiết
if (isset($_POST['id'])) {
    printModal($_POST['id']);
}

$total = 0;

//insert record into IMPORTS talbe
function insert() {
    try {
        //begin transcation
        begin();
        //prepared statement
        $stmt = getConnect()->prepare("INSERT INTO `imports` VALUES (NULL, ?, ?)");
        //insert imports table 
        $stmt->bind_param('ss', $_SESSION['uid'], date('Y-m-d'));
        $stmt->execute();
        //commit
        commit();
        header("location: ../orders_in.php");
        echo $stmt->insert_id;
    } catch (Exception $e) {
        //rollback
        rollback();
    }
}

//delete record in IMPORTS table by id
//delete records in IMPORTS_DETAILS table by import id
function delete($array) {
    //import id
    $arr = explode("=", $array[1]);
    $iid = $arr[1];
    try {
        //begin transcation
        begin();
        //prepared statement
        $stmt = getConnect()->prepare("DELETE FROM imports WHERE id=?");
        $stmt1 = getConnect()->prepare("DELETE FROM imports_details WHERE import=?");
        //delete imports table 
        $stmt->bind_param('i', $iid);
        $stmt->execute();
        //delete imports_details table
        $stmt1->bind_param('i', $iid);
        $stmt1->execute();
        //commit
        commit();
    } catch (Exception $e) {
        //rollback
        rollback();
    }
}

//update record user, date in IMPORTS table by id
//update records product, quantity in IMPORTS_DETAILS by import id
function update($array) {
    //import id
     $arr = explode("=", $array[1]);
     $iid = $arr[1];
    //user id create import
    $uid = getIdInString($array[2]);
    //date import
    //$did = explode("-", $array[3])[2] . "-" . explode("-", $array[3])[1] . "-" . explode("=", explode("-", $array[3])[0])[1];
    $arr1 = explode("-", $array[3]);
    $arr2 = explode("=", $arr1[0]);
    $did = $arr1[2] . "-" . $arr1[1] . "-" . $arr2[1];

    try {
        //begin transcation
        begin();

        //query
        //prepared statement
        $stmt = getConnect()->prepare("UPDATE imports SET user=?,time=? WHERE id=?");
        $stmt1 = getConnect()->prepare("UPDATE imports_details SET product=?,quantity=? WHERE id=?");
        $stmt2 = getConnect()->prepare("INSERT INTO imports_details(import,product,quantity) values(?,?,?)");
        //update import table 

        $stmt->bind_param('isi', $uid, $did, $iid);
        $stmt->execute();
        //update imports_details table
        for ($i = 4; $i < count($array); $i+=3) {

            $arr3 = explode("=", $array[$i]);
            $ipid = $arr3[1];

            $arr4 = explode("=", $array[$i + 1]);
            $pid = getIdInString($arr4[1]);

            $arr5 = explode("=", $array[$i + 2]);
            $quantity = $arr5[1];

            if ($ipid == "NULL") {
                $stmt2->bind_param('iii', $iid, $pid, $quantity);
                $stmt2->execute();
            } else {
                $stmt1->bind_param('iii', $pid, $quantity, $ipid);
                $stmt1->execute();
            }
        }
        //commit
        commit();
    } catch (Exception $e) {
        //rollback
        rollback();
    }
}

function printImportTable() {
    $result = mysqli_query(getConnect(), 'SELECT imports.id, users.name, imports.time   FROM users INNER JOIN imports ON users.id = imports.user');

    $str = "<div class='row'>
                <div class='col-lg-12'>
                    <div class='panel panel-default'>
                        <div class='panel-heading'>
                            Dữ liệu nhập hàng
                        </div>
                        <!-- /.panel-heading -->
                        <div class='panel-body'>
                            <div class='table-responsive'>
                                <table class='table table-striped table-bordered table-hover' id='dataTables-example'>
                                    <thead>
                                        <tr>
                                            <th>Số thứ tự</th>
                                            <th>Tên người nhập</th>
                                            <th>Ngày nhập</th><th></th>
                                            <th>Tổng giá trị</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    ";
    while ($row = mysqli_fetch_array($result)) {
        $date = new DateTime($row['time']);
        $total = getTotalImportById("${row['id']}");
        $str = $str . "                 <tr class = 'odd gradeX'>
                                            <td>${row['id']}</td>
                                            <td>${row['name']}</td>
                                            <td>" . $date->format('d-m-Y') . "</td>
                                            <td>${total}</td>
                                            <td class = 'center'><i class = 'fa fa-wrench fa-fw'></i><button id = 'editButton-${row['id']}' value = 'editButton-${row['id']}' type = button class = 'btn btn-link' data-toggle = 'modal' data-target = '#myModal'>&nbsp;Chi tiết</button></td>
                                        </tr>";
    }

    $str = $str . "                 </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>";

    echo $str;
}

function printImportDetailTable($id) {
    $GLOBALS['total'] = 0;
    $result = mysqli_query(getConnect(), "SELECT imports_details.id as ipid, imports_details.product,imports_details.quantity, products.name, products.id, products.price "
            . "FROM imports_details "
            . "INNER JOIN products ON imports_details.product = products.id "
            . "WHERE imports_details.import='${id}'");

    $str = "<div class='row'>
                <div class='col-lg-12'>
                    <div class='panel panel-default'>
                        <div class='panel-heading'>
                            Chi tiết nhập hàng
                        </div>
                        <!-- /.panel-heading -->
                        <div class='panel-body'>
                            <div class='table-responsive'>
                                <table class='table table-striped table-bordered table-hover' id='dataTables-details'>
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Sản phẩm</th>
                                            <th>Số lượng</th>
                                            <th>Thành tiền</th>
                                        </tr>
                                    </thead>
                                    <tbody>";

    while ($row = mysqli_fetch_array($result)) {
        $sum = $row['quantity'] * $row['price'];
        $GLOBALS['total']+=$sum;
        $str = $str . "                 <tr>
                                            <td style='width:10%'><input style='width:100%' name=ipid value='${row['ipid']}' readonly></td>
                                            <td style='width:60%'><input class='cpid' id ='pid' style='width:100%' onKeyUp = \"loadSuggest(this, 'product');\" onblur=\"changeprice(this);\" name=name value='${row['name']} <${row[id]}>'></td>
                                            <td style='width:15%'><input style='width:100%' name=quantity value='${row['quantity']}' onblur=\"changeprice(this);\"></td>
                                            <td style='width:15%'>${sum}</td>
                                        </tr>";
    }

    $str = $str . "                 </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>";

    return $str;
}

function printModal($id) {
    $result = mysqli_query(getConnect(), "SELECT imports.id as iid, users.name, users.id as uid, imports.time FROM products, users INNER JOIN imports ON users.id = imports.user where imports.id='${id}'");

    while ($row = mysqli_fetch_array($result)) {
        $date = new DateTime($row['time']);
        $str = "<div class='form-group'>
                <label>Số thứ tự</label>
                <input id='iidinfo' class='form-control' value='${row['iid']}' readonly>
                </div>
                <div class='form-group'>
                <label>Người nhập</label>
                <input id='uidinfo' class='form-control' value='${row['name']} <${row['uid']}>' onKeyUp = \"loadSuggest(this, 'user');\">
                </div>
                <div class='form-group'>
                <label>Ngày nhập</label>
                <input id='didinfo' class='form-control' value='" . $date->format('d-m-Y') . "'>
                </div>";

        $str = $str . printImportDetailTable($id) . "
                <div class='form-group'>
                <label>Tổng giá trị đơn hàng: </label>
                <label>${GLOBALS['total']}</label>
                </div>";
    }

    echo $str;
}

function getTotalImportById($id) {
    $result = mysqli_query(getConnect(), "SELECT imports_details.quantity as quantity, products.price as price
                                          FROM imports_details INNER JOIN products ON imports_details.product = products.id
                                          WHERE imports_details.import='{$id}'");
    $sum = 0;
    while ($row = mysqli_fetch_array($result)) {
        $sum += $row['quantity'] * $row['price'];
    }

    return $sum;
}

function getPriceById($id, $quantity) {
    $pid = getIdInString($id);
    $result = mysqli_query(getConnect(), "SELECT price
                                          FROM products
                                          WHERE id='{$pid}'");
    while ($row = mysqli_fetch_array($result)) {
        echo $row['price'] * $quantity;
    }
}

function getIdInString($str) {
    $start = strpos("{$str}", "<");
    $stop = strpos("{$str}", ">");
    return substr($str, $start + 1, $stop - $start - 1);
}
